<?php

namespace backend\models\form;

use backend\service\StoreService;
use common\models\GoodsInfo;
use common\models\Order;
use common\service\BaseToolService;
use common\service\BusinessService;
use common\service\ConstatService;
use common\service\UtilService;
use yii\base\Model;
use Yii ;

class OrderForm extends Model {

    public $store_code;
    public $user_name ;
    public $user_phone;
    public $user_address;
    public $weight;
    public $carrier_no;
    public $package_num;
    public $expectpick_time;
    public $expect_time;
    public $remark;
    public $distince ;
    public $user_logitude ;
    public $user_latiude ;
    public $orderno ;
    public $business_type ;
//    public $product_name ;
//    public $sale_num ;
//    public $unit_price ;


    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['store_code','orderno','user_phone','user_name','user_address','weight','expectpick_time','expect_time','carrier_no','package_num','business_type'],'required'],
            [['store_code','user_name','user_phone','user_address','remark','carrier_no','expect_time','expectpick_time','orderno'], 'string'],
            [['weight','distince','user_logitude','user_latiude'], 'number'],
            [['package_num','business_type'], 'integer'],
            [['orderno'], 'unique', 'targetClass' => '\common\models\Order', 'message' => '订单号已存在'],
            [['store_code'],'validStoreCode'] ,
            [['expectpick_time'],'validExpectpickTime'] ,
            [['user_phone'],'validPhone'] ,
            [['business_type'],'validBusinessType'] ,
            [['weight'],'validWeight'] ,
//            [['product_name','sale_num','unit_price'],'validGoods'] ,
            [['store_code','user_name','user_phone','user_address','remark','carrier_no','expect_time','expectpick_time','weight','package_num','orderno','distince','user_logitude','user_latiude'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],
            [['store_code','user_name','user_phone','user_address','remark','carrier_no','expect_time','expectpick_time','weight','package_num','orderno'],
                'filter','filter'=>'\yii\helpers\HtmlPurifier::process']];
    }

    public function validPhone(){
        $isMob="/^1[0-9]{1}[0-9]{9}$/";
        $isTel="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        if(!preg_match($isMob,$this->user_phone) && !preg_match($isTel,$this->user_phone)){
            $this->addError("user_phone", "请输入手机号或者座机号") ;
            return false ;
        }
    }

    public function validBusinessType(){
        $businessTypeArr = ConstatService::ORDER_BUSINESS_TYPE_DESC ;
        if(empty($businessTypeArr[$this->business_type])){
            $this->addError("business_type", "业务类型不合法") ;
            return false ;
        }
    }


    public function validExpectpickTime(){
        $end = strtotime($this->expect_time) ;
        $start = strtotime($this->expectpick_time) ;
        if($end-$start<3600){
            $this->addError("expectpick_time", "送达时间必须高于上门取货时间一个小时以上") ;
            return false ;
        }
    }

    public function validWeight(){
        if(empty($this->weight)|| $this->weight==0.00){
            $this->addError("weight", "重量必须大于0.00") ;
            return false ;
        }
        //判断位数
        $length = UtilService::getFloatLength($this->weight);
        if($length>2){
            $this->addError("weight", "订单重量小数位超过3位") ;
            return false ;
        }
    }

    public function validStoreCode(){
        if(empty($this->store_code) || $this->store_code == -1 ){
            $this->addError("store_code", "门店编码不能为空") ;
            return false ;
        }
    }

    public function validGoods(){
        if(empty($this->product_name) || empty(count($this->product_name))){
           $this->addError("product_name", "商品名称不能为空") ;
           return false ;
        }

        foreach($this->product_name as $val){
            if(empty($val)){
                $this->addError("product_name", "商品名称不能为空") ;
                return false ;
            }
        }

        if(empty($this->sale_num) || empty(count($this->sale_num))){
            $this->addError("sale_num", "销售数量不能为空") ;
            return false ;
        }

        foreach($this->sale_num as $val){
            if(empty($val)){
                $this->addError("sale_num", "销售数量不能为空") ;
                return false ;
            }
        }

        if(empty($this->unit_price) || empty(count($this->unit_price))){
            $this->addError("unit_price", "商品单价不能为空") ;
            return false ;
        }

        foreach($this->unit_price as $val){
            if(empty($val)){
                $this->addError("sale_num", "商品单价不能为空") ;
                return false ;
            }
        }
    }

    public function attributeLabels() {
        return [
            'orderno' => '订单号' ,
            'store_code'=>'门店编码',
            'user_name'=>'收件人姓名',
            'user_phone'=>'收件人电话',
            'user_address'=>'收件人地址',
            'remark'=>'备注',
            'carrier_no'=>'取货号',
            'expect_time'=>'送达时间',
            'expectpick_time'=>'天虹要求上门取货时间',
            'weight'=>'订单总重量',
            'package_num'=>'包数量',
            'user_logitude' => '收件人经度',
            'user_latiude' => '收件人纬度',
            'distince' => '骑行距离',
            'business_type' => '业务分类',
//            'product_name' => '商品名称',
//            'sale_num' => '销售数量',
//            'unit_price' => '商品单价',
        ] ;
    }

    /**
     * 建立订单
     * @return array
     */
    public function createOrder(){
        $connection = Yii::$app->db->beginTransaction();
        try {
            $logisticsCode               = UtilService::getSystemParamByKey("logistics_code", null);//物流商编码
            $order                       = new Order();
            $time                        = date("Y-m-d H:i:s");
            $order->logistics_code       = $logisticsCode;
            $order->opt_time             = $time;
            $order->receive_th_data_time = $time;
            $order->orderno              = $this->orderno;
            $order->store_code           = $this->store_code;
            $order->user_name            = $this->user_name;
            $order->user_phone           = $this->user_phone;
            $order->user_address         = $this->user_address;
            $order->weight               = $this->weight;
            $order->carrier_no           = $this->carrier_no;
            $order->package_num          = $this->package_num;
            $order->expectpick_time      = $this->expectpick_time;
            $order->expect_time          = $this->expect_time;
            $order->remark               = $this->remark;
            $order->source               = ConstatService::ORDER_SOURCE_INPUT;
            $order->status               = ConstatService::ORDER_DISTRIBUTION;
            //以下三个参数 需要调用高德API获取
            $order->user_logitude = $this->user_logitude;
            $order->user_latiude  = $this->user_latiude;
            $order->distince      = $this->distince;
            $order->sign_scope    = UtilService::getSystemParamByKey("sign_scope", 300);
            $order->business_type = $this->business_type ;

            $createRs = $order->save();
            if($createRs!=true){
                $connection->rollBack();
                $msg = current($order->getFirstErrors()) ;
                return ["code"=>400,"msg"=>"失败,原因:".$msg] ;
            }

            $logArr['orderno'] = $this->orderno;
            $logArr['status']  = ConstatService::ORDER_DISTRIBUTION;
            $logArr['remark']  = "后台立即发单" ;
            BusinessService::addOrderlog($logArr) ;

//            foreach ($this->product_name as $key => $val) {
//                $goodInfo               = new GoodsInfo();
//                $goodInfo->orderno      = $this->orderno;
//                $goodInfo->product_name = $val;
//                $goodInfo->sale_num     = $this->sale_num[$key];
//                $goodInfo->unit_price   = $this->unit_price[$key];
//                $rs = $goodInfo->save();
//                if($rs!=true){
//                    $connection->rollBack();
//                    $msg = current($goodInfo->getFirstErrors()) ;
//                    return ["code"=>400,"msg"=>"失败,原因:".$msg] ;
//                }
//            }

            $connection->commit() ;
            return ["code"=>200,"msg"=>"成功"] ;

        }catch (\Exception $e){
            $logArr = ["e"    =>  $e] ;
            BaseToolService::error($logArr,"OrderForm_createOrder_errror") ;
            $connection->rollBack();
            return ["code"=>400,"msg"=>"建立订单异常"] ;
        }
    }


    /**
     * 验证批量
     * @return array
     */
    public function batchSave($datas){

        $stores = StoreService::findAllStoreByCode() ;
        $tag = false ;

        $storeCode = Yii::$app->admin->identity->store_code ;
        $typeId = Yii::$app->admin->identity->type_id ;

        foreach($datas as $key=>$data){
            if($typeId==ConstatService::ROLE_TH_STORE_MANAGER || $typeId==ConstatService::ROLE_HQ_STORE_MANAGER){
                if(!empty($data["C"])){
                    return ["code"=>400,"msg"=>$data["B"]."该订单:不需要录入门店编号"];
                }
            }
            //天虹门店人员不需要录入门店编号,取用户关联的门店编号
            if($typeId==ConstatService::ROLE_TH_STORE_MANAGER || $typeId==ConstatService::ROLE_HQ_STORE_MANAGER){
                $data["C"] = $storeCode ;
            }

            $logisticsCode               = UtilService::getSystemParamByKey("logistics_code", null);//物流商编码
            $order                       = new Order();
            $time                        = date("Y-m-d H:i:s");
            $order->logistics_code       = $logisticsCode;
            $order->opt_time             = $time;
            $order->receive_th_data_time = $time;
            $order->business_type        = $data["A"];
            $order->orderno              = $data["B"];
            $order->store_code           = $data["C"];
            $order->user_name            = $data["E"];
            $order->user_phone           = $data["F"];
            $order->user_address         = $data["D"];
            $order->weight               = $data["I"];
            $order->carrier_no           = $data["G"];
            $order->package_num          = $data["H"];
            $order->expectpick_time      = $data["J"];
            $order->expect_time          = $data["K"];
            $order->remark               = $data["L"];
            $order->source               = ConstatService::ORDER_SOURCE_EXPORT;
            $order->status               = ConstatService::ORDER_DISTRIBUTION;
            $order->sign_scope           = UtilService::getSystemParamByKey("sign_scope", 300);

            $rs = UtilService::getLocation($order->user_address) ;
            if($rs['code']!=200){
                return ["code"=>400,"msg"=>$data["B"]."该订单:".$rs['msg']];
            }

            if(empty($stores[$order->store_code])){
                return ["code"=>400,"msg"=>$data["B"]."该订单:"."门店不合法"];
            }

            $storeLatiude = $stores[$order->store_code]['latitude'] ;
            $storeLogitude = $stores[$order->store_code]['longitude'] ;


            $logitude = $rs['logitude'] ;
            $latiude  = $rs['latiude'] ;

            $rs = UtilService::getDistance($storeLatiude,$storeLogitude,$latiude,$logitude) ;

            if($rs['code']!=200){
                return ["code"=>400,"msg"=>$data["B"]."该订单:".$rs['msg']];
            }

            $distance = $rs['distance'] ;

            //以下三个参数 需要调用高德API获取
            $order->user_logitude = $logitude;
            $order->user_latiude  = $latiude;
            $order->distince      = $distance;

            $validRs = $order->validate();
            if($validRs!=true){
                $error = current($order->getFirstErrors());
                return ["code"=>400,"msg"=>$data["B"]."该订单:".$error];
            }
            $tag = true ;
        }

        $num = 0 ;
        if($tag==true){
            foreach($datas as $key=>$data){
                //天虹门店人员不需要录入门店编号,取用户关联的门店编号
                if($typeId==ConstatService::ROLE_TH_STORE_MANAGER || $typeId==ConstatService::ROLE_HQ_STORE_MANAGER){
                    $data["C"] = $storeCode ;
                }
                $logisticsCode               = UtilService::getSystemParamByKey("logistics_code", null);//物流商编码
                $order                       = new Order();
                $time                        = date("Y-m-d H:i:s");
                $order->logistics_code       = $logisticsCode;
                $order->opt_time             = $time;
                $order->receive_th_data_time = $time;
                $order->business_type        = $data["A"];
                $order->orderno              = $data["B"];
                $order->store_code           = $data["C"];
                $order->user_name            = $data["E"];
                $order->user_phone           = $data["F"];
                $order->user_address         = $data["D"];
                $order->weight               = $data["I"];
                $order->carrier_no           = $data["G"];
                $order->package_num          = $data["H"];
                $order->expectpick_time      = $data["J"];
                $order->expect_time          = $data["K"];
                $order->remark               = $data["L"];
                $order->source               = ConstatService::ORDER_SOURCE_EXPORT;
                $order->status               = ConstatService::ORDER_DISTRIBUTION;

                $rs = UtilService::getLocation($order->user_address) ;
                if($rs['code']!=200){
                    continue ;
                }

                $storeLatiude = $stores[$order->store_code]['latitude'] ;
                $storeLogitude = $stores[$order->store_code]['longitude'] ;


                $logitude = $rs['logitude'] ;
                $latiude  = $rs['latiude'] ;

                $rs = UtilService::getDistance($storeLatiude,$storeLogitude,$latiude,$logitude) ;

                if($rs['code']!=200){
                    return ["code"=>400,"msg"=>$data["B"]."该订单:".$rs['msg']];
                }

                $distance = $rs['distance'] ;

                //以下三个参数 需要调用高德API获取
                $order->user_logitude = $logitude;
                $order->user_latiude  = $latiude;
                $order->distince      = $distance;

                $validRs = $order->save();
                if($validRs!=true){
                    $error = current($order->getFirstErrors());
                    continue ;
                }

                $logArr['orderno'] = $order->orderno;
                $logArr['status']  = ConstatService::ORDER_DISTRIBUTION;
                $logArr['remark']  = "后台批量发单" ;
                BusinessService::addOrderlog($logArr) ;

                $num = $num + 1 ;
            }
        }

        return ["code"=>200,"msg"=>"成功","num"=>$num] ;


    }
}
